from flask import Flask, request, jsonify, abort
from Tools import DecodeAllTextByAESCBC, Bxor, HmacBack, EncodeAllTextByAESCBC
import sqlite3
import base64

app = Flask(__name__)

#测试接口
@app.route('/a', methods=['GET', 'POST'])
def home():
    return jsonify({'result': 'success'})

#存储
@app.route("/test",methods=["POST"])
def check():
    if request.args["id"] is None or request.args["text"] is None or request.args["key"] is None:
        abort(1111)
    #获得参数
    id = request.args["id"]
    text = request.args["text"]
    key = request.args["key"]
    
    #转为bytes
    text = bytes(text, encoding="utf-8")
    text = base64.b64decode(text)

    key = bytes(key, encoding="utf-8")
    key = base64.b64decode(key)
    
    #传输解密
    text = DecodeAllTextByAESCBC(text)
    key = DecodeAllTextByAESCBC(key)
   
    #数据库存储部分 
    
    return jsonify({'result': 'success'})
 
@app.route("/find",methods=["POST"])
def find():
    if request.args["id"] is None or request.args["k"] is None or request.args["key"] is None:
        abort(2222)
    #获得参数
    k = request.args["k"]
    findkey = request.args["key"]
    id = request.args["id"]

    #解密+消0
    findkey = bytes(findkey, encoding="utf-8")
    findkey = base64.b64decode(findkey) 
    findkey = DecodeAllTextByAESCBC(findkey)

    k = bytes(k, encoding="utf-8")
    k = base64.b64decode(k)
    k = DecodeAllTextByAESCBC(k)
    while(k[len(k)-1] == 48):
        k = k[:(len(k)-1)]
    #数据库查询部分
    
    ##save为查询结果
    #遍历结果，查询陷门
    ans = []
    for i in save:
        a = i[0]
        #逐段匹配
        while(len(a) != 0):
            #陷门匹配部分
            b = a[:48]
            a = a[48:]
            #数据匹配部分


            if(fk == tr):
                #找到了
                transtext = i[1]
                transkey = i[0]
               
                #text传输加密
                transtext = EncodeAllTextByAESCBC(transtext)
                transtext = base64.b64encode(transtext)
                transtext = str(transtext, encoding="utf-8")

                #key传输加密
                transkey = EncodeAllTextByAESCBC(transkey)
                transkey = base64.b64encode(transkey)
                transkey = str(transkey, encoding="utf-8")
               
                #参数,json
                find = {
                   "text" : transtext,
                   "key" : transkey
                }
                ans.append(find)
                a = b""
    

    #返回结果
    if(len(ans) == 0):
        return jsonify(
            {"ans" : "www"})
    else:
        return jsonify(
            {"ans" : ans})
    

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=5000, debug=True)